/************************************************************************************
* TrackBrowser.cpp                                                                        *
*                                                                                   *
* Copyright (C) 2011 Varuna L Amachi                                              *
*                                                                                   *
* This program is free software; you can redistribute it and/or modify              *
* it under the terms of the GNU General Public License as published by              *
* the Free Software Foundation; either version 2 of the License, or any             *
* later version.                                                                    *
*                                                                                   *
* This program is distributed in the hope that it will be useful, but               *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY        *
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for       *
* more details. You should have received a copy of the GNU General Public           *
* License along with this program; if not, write to the Free Software Foundation,   *
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA                       *
*                                                                                   *
*************************************************************************************/ 

#include "TrackBrowser.h"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QSplitter>
#include <QHeaderView>

using namespace Yamp;

TrackBrowser::TrackBrowser(YContext *context, QWidget *parent):
    YampComponent(context, parent)
{
    m_artistModel = new ArtistModel(this);
    m_albumModel  = new AlbumModel(this);
    m_trackModel  = new PartialCollectionModel(this);
    m_artistView = new QTreeView(this);
    m_albumView  = new QTreeView(this);
    m_trackView  = new SimpleCollectionView(m_trackModel,
                                            new SimpleCollectionSortFilter(m_context, this),
                                            this,
                                            false);  //Dont show the filter bar
    m_artistProxy = new ArtistSortFilterModel(context, this);
    m_albumProxy = new AlbumSortFilterModel(context, this);
    m_artistFilter = new SearchBox(this);
//    m_albumFilter = new SearchBox(this);
    m_artistModel->setModel(Collector::get()->allArtists());
    setupUi();
    setupActions();
    setupConnections();
    setupStyle();
}


void TrackBrowser::setupUi() {

    m_artistProxy ->setSourceModel(m_artistModel);
    m_artistProxy->setDynamicSortFilter(true);
    m_albumProxy->setSourceModel(m_albumModel);
    m_albumProxy->setDynamicSortFilter(true);

    m_artistView->setModel(m_artistProxy);
    m_artistView->setAlternatingRowColors(true);
    m_artistView->setSortingEnabled(true);
    m_artistView->setWordWrap(false);
    m_artistView->setAutoScroll(true);
    m_artistView->setRootIsDecorated(false);
    m_artistView->header()->setStretchLastSection(false);
    m_artistView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    m_artistView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_artistView->setFocusPolicy(Qt::WheelFocus);
    m_artistView->header()->setResizeMode(0, QHeaderView::Stretch);

    m_albumView->setModel(m_albumProxy);
    m_albumView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    m_albumView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_albumView->setFocusPolicy(Qt::WheelFocus);
    m_albumView->header()->setResizeMode(1, QHeaderView::Stretch);
    m_albumView->setAlternatingRowColors(true);
    m_albumView->setSortingEnabled(true);
    m_albumView->setWordWrap(false);
    m_albumView->setAutoScroll(true);
    m_albumView->setRootIsDecorated(false);
    m_albumView->setColumnHidden(0, true);
    m_albumView->header()->setStretchLastSection(false);
    m_albumView->setColumnWidth(2, 50);
    m_albumView->setColumnWidth(3, 50);
    m_albumView->setColumnWidth(4, 25);

    m_artistProxy->sort(0);
    m_albumProxy->sort(1);
    m_trackModel->sort(0);


    QHBoxLayout *filterLyt = new QHBoxLayout();
    filterLyt->addWidget(new QLabel(tr("Filter Artist"), this));
    filterLyt->addWidget(m_artistFilter);


    QList<int> sizes;
    sizes << 140 << 200;

    QSplitter *horzSplit = new QSplitter(Qt::Horizontal, this);
    horzSplit->addWidget(m_artistView);
    horzSplit->addWidget(m_albumView);
    horzSplit->setSizes(sizes);

    QSplitter *vertSplit = new QSplitter(Qt::Vertical, this);
    vertSplit->addWidget(horzSplit);
    vertSplit->addWidget(m_trackView);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->addLayout(filterLyt);
    mainLayout->addWidget(vertSplit);
    this->setLayout(mainLayout);
}


void TrackBrowser::setupActions() {
    m_actAddArtist = new QAction(tr("Add to playlist"), m_artistView);
    m_actAddAlbum = new QAction(tr("Add to playlist"), m_albumView);
    m_actAddTracks = new QAction(tr("Add to playlist"), m_trackView);
    connect(m_actAddArtist, SIGNAL(triggered()), this, SLOT(onAddArtistToPlaylist()));
    connect(m_actAddAlbum, SIGNAL(triggered()), this, SLOT(onAddAlbumToPlaylist()));
    connect(m_actAddTracks, SIGNAL(triggered()), this, SLOT(onAddTracksToPlaylist()));


    m_artistView->addAction(m_actAddArtist);
    m_albumView->addAction(m_actAddAlbum);
//    m_trackView->addAction();
    QList<QAction*>* act = new QList<QAction*>();
    act->append(m_actAddTracks);
    m_trackView->setContextActions(act);

}

TrackBrowser::~TrackBrowser() {

}


void TrackBrowser::setupConnections() {
    connect(m_artistView, SIGNAL(clicked(QModelIndex)),  this, SLOT(onArtistSelected()));
//    connect(m_albumView, SIGNAL(clicked(QModelIndex)), this, SLOT(onAlbumSelected()));

    connect(m_albumView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(onAlbumSelected()));
//    connect(m_artistView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
//            this, SLOT(onArtistSelected()));
    connect(m_trackView, SIGNAL(itemActivated(CollectorItem*)), this, SLOT(onTrackSelected(CollectorItem*)));
    connect(Collector::get(), SIGNAL(collectionDeletionStarted()), this, SLOT(allModelClean()));
    connect(Collector::get(), SIGNAL(collectionDeletionEnded()), this, SLOT(allModelUpdate()));
    connect(Collector::get(), SIGNAL(itemsAdded(QList<CollectorItem*>*)), this, SLOT(allModelUpdate()));
    connect(m_artistFilter, SIGNAL(textChanged(QString)), this, SLOT(applyFilter()));
    connect(m_artistView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(onAddArtistToPlaylist()));
    connect(m_albumView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(onAddAlbumToPlaylist()));
}

QString TrackBrowser::name() {
    return tr("Collection");
}


void TrackBrowser::onArtistSelected() {
    QModelIndexList indexList = m_artistView->selectionModel()->selectedRows(0);
    QList<AlbumInfo *> albums;
    QString artist = indexList.at(0).data().toString();
    artist = (artist == NOT_AVAILABLE? "" : artist);
    Collector::get()->albumsFromArtist(artist, albums);
    m_albumModel->setModel(albums);
    selectRow(m_albumView, 0);
}


void TrackBrowser::onAlbumSelected() {
    QString artist = m_albumView->selectionModel()->selectedRows(0).at(0).data().toString();
    artist = (artist == NOT_AVAILABLE? "" : artist);
    QModelIndexList indexList = m_albumView->selectionModel()->selectedRows(1);
    QList<CollectorItem *> *items = new QList<CollectorItem *>;
    foreach(QModelIndex index, indexList) {
        if(index.data().toString() == ALL_ALBUMS) {
            //If "All" entry is selected get everything from that artist dont bother about
            //iterating to all albums
            items->clear();
            Collector::get()->itemsFromArtist(artist, *items);
            break;
        }
        else {
            QString album = (index.data().toString() == NOT_AVAILABLE? "" : index.data().toString());
            Collector::get()->itemsFromAlbum(album, artist, (*items));
        }
    }
    m_trackModel->setModel(items);
}

void TrackBrowser::onTrackSelected(CollectorItem *item) {
    m_context->playlist()->append(item, true);
}


void TrackBrowser::playStarted(MediaItem *item) {
    m_albumView->repaint();
}


void TrackBrowser::setupStyle() {

}


void TrackBrowser::ratingChanged(MediaItem *item, MediaRating rating) {
    m_albumView->repaint();
}


void TrackBrowser::applyFilter() {
    QString regEx = m_artistFilter->text();
//    m_albumProxy->setExpression(regEx);
    m_artistProxy->setExpression(regEx);
//    m_trackView->setFilterExpression(regEx);
}

void TrackBrowser::allModelClean() {
    m_trackModel->setModel(new QList<CollectorItem *>());
    m_albumModel->setModel(QList<AlbumInfo *>());
    m_artistModel->setModel(QList<ArtistInfo *>());
}


void TrackBrowser::allModelUpdate() {
   m_artistModel->setModel(Collector::get()->allArtists());
   selectRow(m_artistView, 0);
}

void TrackBrowser::selectRow(QTreeView *view, int index) {
    QItemSelectionModel *selection = view->selectionModel();
    selection->select (
        QItemSelection (
            view->model ()->index (index, 0),
            view->model ()->index (index, view->model ()->columnCount () - 1)),
        QItemSelectionModel::Select);
    view->scrollTo(view->model ()->index (index, 0));
}


void TrackBrowser::onAddArtistToPlaylist() {
    QModelIndexList indexList = m_artistView->selectionModel()->selectedRows(0);
    QList<CollectorItem *> items;
    foreach(QModelIndex index, indexList)     {
        QString artist = index.data().toString();
        Collector::get()->itemsFromArtist(artist, items);
    }
    QList<MediaItem *> *medias = new QList<MediaItem *>();
    for(int i = 0; i < items.size(); i++) {
        medias->append((MediaItem*)items[i]);
    }
    m_context->playlist()->append(medias, false);

}

void TrackBrowser::onAddAlbumToPlaylist() {
    QModelIndexList albumList = m_albumView->selectionModel()->selectedRows(1);
    QModelIndexList artistList=  m_albumView->selectionModel()->selectedRows(0);
    QList<CollectorItem *> items;
    for(int i = 0; i < albumList.size(); ++i) {
        QString album = albumList.at(i).data().toString();
        QString artist = artistList.at(i).data().toString();
        Collector::get()->itemsFromAlbum(album, artist, items);
    }
//    for(int i = 0; i < items->size(); i++) {
//        m_context->playlist()->append(dynamic_cast<MediaItem *>(items->at(i)));
//    }
    QList<MediaItem *> *medias = new QList<MediaItem *>();
    for(int i = 0; i < items.size(); i++) {
        medias->append((MediaItem*)items[i]);
    }
    m_context->playlist()->append(medias, false);
}

void TrackBrowser::onAddTracksToPlaylist() {
    QList<QString> *selected = m_trackView->selectedTrackIds();
    for(int i = 0; i < selected->size(); ++i) {
        m_context->playlist()->append(Collector::get()->item(selected->at(i)), false);
    }
    delete selected;
}
